package com.example.online_chat.api;

import com.example.online_chat.model.User;
import com.example.online_chat.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
public class UserAPI {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest req) {
        User user = userMapper.selectUserByName(username);

        if (user == null || !user.getPassword().equals(password)) {
            System.out.println("登录失败, 用户名或密码错误!");
            return new User();
        }

        // 创建会话
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        user.setPassword("");
        return user;
    }

    @PostMapping("/register")
    public Object register(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        try {
            userMapper.addUser(user);
        } catch (DuplicateKeyException e) {
            System.out.println("注册失败, username = " + username);
            return new User();
        }
        user.setPassword("");
        return user;
    }

    @GetMapping("/userInfo")
    public Object getUserInfo(@SessionAttribute("user") User user) {
        user.setPassword("");
        return user;
    }
}
